﻿using System;
using System.Collections.Generic;
using System.Linq;
using BLL;
using Logic.BusinessLogic.SocialNetworks;

namespace Logic.BusinessLogic
{
    public class PostingResult : Utils.ServiceResponse
    {
        public SocialNetworks.SnSelector PublishedNetworks { get; set; }

        public int AccountID { get; set; }

        public PostingResult()
        {
            this.PublishedNetworks = new SocialNetworks.SnSelector();
            this.ResultOption = Utils.ServiceResultOptions.OperationFailure;
        }
    }

    public class Posting
    {
        /// <summary>
        /// Posts a status line to a number of accounts
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="accountIDs"></param>
        /// <param name="text"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        public static List<PostingResult> PostToAccounts(int userID, IEnumerable<int> accountIDs, string text, SocialNetworks.SnSelector sn, bool postAsLInk)
        {
            var result = new List<PostingResult>();
            foreach (var accountID in accountIDs)
            {
                if (postAsLInk)
                    result.Add(PostLink(userID, accountID, text, sn));
                else
                    result.Add(PostStatusLine(userID, accountID, text, sn));
            }
            return result;
        }

        public static List<List<PostingResult>> POstToMasterAccounts(int userID, IEnumerable<BO.MasterAccount> accounts, string text, SocialNetworks.SnSelector sn, bool postAsLInk)
        {
            var result = new List<List<PostingResult>>();
            foreach (var mAccount in accounts)
            {
                // FIXME: add a condition to prevent null exception if the master account doesn't have any sub accounts
                IEnumerable<int> ids = mAccount.Accounts.Select(a => a.ID);
                result.Add(PostToAccounts(userID, ids, text, sn, postAsLInk));
            }
            return result;
        }

        public static PostingResult PostStatusLine(int userID, int accountID, string text, SocialNetworks.SnSelector sn)
        {
            PostingResult response = new PostingResult { AccountID = accountID };
            var account = BLL.Accounts.GetByID(accountID);
            var post = new BO.Post
            {
                AccountID = accountID,
                PostType = BO.Post.PostTypes.StatusLine,
                PostingUserID = userID,
                EntityStatus = BLL.EntityStatuses.Active,
                TimePosted = DateTime.Now,
                Text = text
            };

            post.Insert();

            if (sn.IsFacebook)
            {
                var result = SocialNetworks.Posting.PostTextToFacebook(account.FbPublishingToken, text);
                response.PublishedNetworks.IsFacebook = result.ResultOption == Social.ServiceResultOptions.Success;
                post.FbItemID = result.Content;
            }

            if (sn.IsTwitter)
            {
                var result = SocialNetworks.Posting.PostTextToTwitter(account.TwToken, account.TwSecret, text);
                response.PublishedNetworks.IsTwitter = result.ResultOption == Social.ServiceResultOptions.Success;
                post.TwStatusId = result.Content;
            }

            post.Update();
            return response;
        }

        public static BO.Post InsertVideoToDB(string title, string description, int userID, int accountID, SnSelector snSelector)
        {
            BO.Post item = new BO.Post { TimePosted = DateTime.Now, Text = description, Title = title, PostingUserID = userID, AccountID = accountID, PostType = BO.Post.PostTypes.Video };
            item.Insert();

            CreateUnprocessedPost(item, snSelector);

            return item;
        }

        public static void CreateUnprocessedPost(BO.Post post, SocialNetworks.SnSelector snSelector)
        {
            BO.UnProcessedPost upp = new BO.UnProcessedPost
            {
                PostID = post.ID,
                ProcessStatus = BO.UnProcessedPost.ProcessStatuses.Unprocessed
            };

            upp.SetSnSelection(snSelector);

            upp.Insert();
        }

        public static void UpdateUnprocessedPost(long postID, BO.UnProcessedPost.ProcessStatuses status, string comment)
        {
            var upp = GetUnProcessedPostForPost(postID);
            upp.ProcessStatus = status;
            upp.Comment = comment;
            upp.Update();
        }

        public static BO.UnProcessedPost GetUnProcessedPostForPost(long postID)
        {
            return UnProcessedPosts.Get()
                                .Where(UnProcessedPosts.Columns.PostID, Actions.Equal, postID)
                                .OrderBy(UnProcessedPosts.Columns.ID, true)
                                .SelectOne();
        }

        public static PostingResult PostLink(int userID, int accountID, string text, SocialNetworks.SnSelector sn, string title = "")
        {
            PostingResult response = new PostingResult { AccountID = accountID };
            var account = BLL.Accounts.GetByID(accountID);
            var post = new BO.Post
            {
                AccountID = accountID,
                PostType = BO.Post.PostTypes.Link,
                PostingUserID = userID,
                EntityStatus = BLL.EntityStatuses.Active,
                TimePosted = DateTime.Now,
                Text = text
            };

            post.Insert();

            if (sn.IsFacebook)
            {
                var result = SocialNetworks.Posting.PostLinkToFacebook(account.FbPublishingToken, text);
                response.PublishedNetworks.IsFacebook = result.ResultOption == Social.ServiceResultOptions.Success;
                post.FbItemID = result.Content;
            }

            if (sn.IsTwitter)
            {
                var result = SocialNetworks.Posting.PostTextToTwitter(account.TwToken, account.TwSecret, text);
                response.PublishedNetworks.IsTwitter = result.ResultOption == Social.ServiceResultOptions.Success;
                post.TwStatusId = result.Content;
            }

            //if (sn.IsWordPress)
            //{
            //    var result = SocialNetworks.Posting.PostTextToWordPress(account, title, text);
            //    response.PublishedNetworks.IsWordPress = result.ResultOption == Social.ServiceResultOptions.Success;
            //    post.WpPostID = result.Content;
            //}

            post.Update();
            return response;
        }
    }
}